package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.MyContext;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    /**
     * 添加商品到购物车
     * @param shoppingCart
     */
    @Override
    public ShoppingCart addShoppingCart(ShoppingCart shoppingCart) {

        //添加购物车
        //先根据user_id和dish_id查询购物车里面有没有该菜品或套餐(因为套餐和菜品只能传来一个,所以直接and链接全部)
        Long userId = MyContext.getLoginId();
        LambdaQueryWrapper<ShoppingCart> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(ShoppingCart::getUserId,userId)
                .eq(shoppingCart.getDishId() != null,ShoppingCart::getDishId,shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null,ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        ShoppingCart one = this.getOne(lqw1,false);
        //有菜品或套餐将数量＋1
        if (one != null){
            one.setNumber(one.getNumber() + 1);
            this.updateById(one);
            return one;
        }
        else {
            //没有菜品则新增
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(userId);
            this.save(shoppingCart);
            return shoppingCart;

        }



    }

    @Override
    public void sub(ShoppingCart shoppingCart) {
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();

        Long userId = MyContext.getLoginId();


        //减掉商品之前先查询购物车商品或套餐的数量
        //大于1数量-1,等于1则直接删除
        LambdaQueryWrapper<ShoppingCart> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(ShoppingCart::getUserId,userId)
                .eq(dishId != null,ShoppingCart::getDishId,dishId)
                .eq(setmealId != null,ShoppingCart::getSetmealId,setmealId);
        ShoppingCart one = this.getOne(lqw1, false);
        Integer number = one.getNumber();

        if (number > 1){
            one.setNumber(number-1);
            this.updateById(one);
        }
        else {

            this.removeById(one);
        }

    }
}
